#include <QHostAddress>
#include <QMessageBox>
#include "cmytcpclient.h"

CMyTCPClient::CMyTCPClient()
{
    m_flagConnected = false;
    m_tcpSet.targetIP = "";

    connect(&m_tcpClient, SIGNAL(connected()),
            this, SLOT(slotConnect()));
    connect(&m_tcpClient, SIGNAL(disconnected()),
            this, SLOT(slotDisConnect()));
    connect(&m_tcpClient, SIGNAL(readyRead()),
            this, SLOT(processPendingDatagrams()));
    connect(&m_tcpClient, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));
}

CMyTCPClient::~CMyTCPClient()
{
    m_flagConnected = false;
    m_tcpSet.targetIP = "";
    if (m_tcpClient.isOpen())
        m_tcpClient.close();
}

void CMyTCPClient::SetParam(TCPCSetStruct set)
{
    m_tcpSet = set;
}

bool CMyTCPClient::OpenTcpC()
{
    m_tcpClient.connectToHost(m_tcpSet.targetIP, m_tcpSet.targetPort);
    m_flagConnected = false;
    return true;
}

void CMyTCPClient::CloseTcpC()
{
    m_tcpClient.disconnectFromHost();
//    if (m_tcpClient.state() == QAbstractSocket::UnconnectedState ||
//            m_tcpClient.waitForDisconnected(1000))
//        qDebug("Disconnected!");

    m_flagConnected = false;
}

int CMyTCPClient::SendData(const char *data, int len)
{
    if (data == NULL || len <= 0)
        return -1;

    if (m_flagConnected)
    {
        return m_tcpClient.write(data, len);
    }
    return -1;
}

bool CMyTCPClient::IsConnected()
{
    return m_flagConnected;
}

TCPCSetStruct CMyTCPClient::GetParam()
{
    return m_tcpSet;
}

void CMyTCPClient::processPendingDatagrams()
{
    QByteArray buff;
    QString ip;
    quint16 port;

    while (m_tcpClient.bytesAvailable())
    {
        buff = m_tcpClient.readAll();
        ip = m_tcpClient.peerAddress().toString();
        port = m_tcpClient.peerPort();
//        qDebug()<<"ORIGNAL Data:"<<buff.data();
        emit sigReceiveMsg(buff.data(), buff.count(), ip, port);
    }
}

void CMyTCPClient::displayError(QAbstractSocket::SocketError error)
{
//    if (error == QTcpSocket::RemoteHostClosedError)
//        return;
    QString errStr(m_tcpClient.errorString());
//    qDebug()<<"CMyTCPClient TCPC:"<<errStr;
   if (m_tcpClient.isOpen())
        m_tcpClient.close();
   emit sigConnectError(errStr);

}

void CMyTCPClient::slotConnect()
{
    m_flagConnected = true;
    qDebug()<<"CMyTCPClient: IP:"<<m_tcpClient.localAddress().toString()
           <<"Port:"<<m_tcpClient.localPort();
    emit sigConnectSucess(m_tcpClient.localAddress().toString(),
                          m_tcpClient.localPort());
}

void CMyTCPClient::slotDisConnect()
{
    m_flagConnected = false;
    emit sigDisConnect();
}
